package com.alinesno.cloud.operation.cmdb.third.email.impl;

import java.util.List;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.alinesno.cloud.operation.cmdb.common.constants.EmailSendStatus;
import com.alinesno.cloud.operation.cmdb.common.util.DateUtil;
import com.alinesno.cloud.operation.cmdb.entity.EmailEntity;
import com.alinesno.cloud.operation.cmdb.repository.EmailRepository;
import com.alinesno.cloud.operation.cmdb.third.email.EmailService;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * 发送邮件服务
 * 
 * @author LuoAnDong
 * @since 2018年8月27日 上午7:57:09
 */
@Service
public class EmailServiceImpl implements EmailService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private EmailRepository emailRepository ; 

	@Value("${email.aliyun.access-key}")
	private String aliyunKey ;  //key
	
	@Value("${email.aliyun.access-key-secret}")
	private String aliyunSecret;  //密钥
	
	@Value("${email.aliyun.account-name}")
	private String emailAccountName ; //邮件发送地址 
	
	@Value("${email.aliyun.tag}")
	private String emailTag ; //邮件标签
	
	@Value("${email.aliyun.single-max}")
	private int singleMaxSend ; //邮件标签
	
	@Value("${email.aliyun.from-alias}")
	private String fromAlias ; //邮件标签

	@Override
	public ResponseBean<String> sendSingleEmail(String email, String subject, String htmlBody) {
		return this.sendSingleEmail(new String[] {email}, subject, htmlBody);
	}

	@Override
	public ResponseBean<String> sendSingleEmail(String[] email, String subject, String htmlBody) {
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunKey ,  aliyunSecret);
		IAcsClient client = new DefaultAcsClient(profile);
		
		SingleSendMailRequest request = new SingleSendMailRequest();
		
		try {
			request.setAccountName(emailAccountName);
			request.setFromAlias(fromAlias);
			request.setAddressType(1);
			request.setTagName(emailTag);
			request.setReplyToAddress(true);
			request.setToAddress(arrayToList(email));
			request.setSubject(subject);
			request.setHtmlBody(htmlBody);
			
			SingleSendMailResponse httpResponse = client.getAcsResponse(request);
		
			logger.debug("email response = {}" , ToStringBuilder.reflectionToString(httpResponse));
			ResponseBean<String> r = ResultGenerator.genSuccessMessage("邮件发送成功") ; 
			r.setData(httpResponse.getRequestId()) ; 
			
			return r ;
		} catch (ServerException e) {
			logger.debug("邮件服务器异常:{}" , e.getMessage());
		} catch (ClientException e) {
			logger.debug("邮件发送异常:{}" , e.getMessage());
		}
		return null;
	}

	/**
	 * 数组转换成邮件
	 * @param email
	 * @return
	 */
	private String arrayToList(String[] email) {
		String emailStr = "" ; 
		int length = email.length>singleMaxSend?singleMaxSend:email.length ; 
		for(int i = 0  ; i < length ; i ++) {
			emailStr += email[i] ; 
			if(i != email.length -1) {
				emailStr += "," ; 
			}
		}
		logger.debug("邮件列表:{}" , emailStr);
		return emailStr ;
	}

	@Override
	public List<EmailEntity> findLimit(int maxSendSize) {
		Page<EmailEntity> page = emailRepository.findAllByRendStatus(EmailSendStatus.SEND.getValue() ,PageRequest.of(0, maxSendSize , Sort.by(Direction.DESC , "addTime"))) ; 
		return page.getContent() ; 
	}

	@Override
	public void update(EmailEntity e) {
		emailRepository.save(e) ; 
	}

	@Override
	public int findDaySend(EmailSendStatus emailSendStatus) {
		String date = DateUtil.getChinesePatternNow() ; 
		int count = emailRepository.countByRendStatusAndDate(emailSendStatus.getValue() ,date) ; 
		return count ;
	}
	

}
